/*******************************************************************************
*  file    : git.cpp
*  created : 29.09.2012
*  author  : Slyshyk Oleksiy (alex312@meta.ua)
*******************************************************************************/

#include "git.hpp"
#include "utils.hpp"

#include <QDebug>
#include <QProcess>
#include <QTemporaryFile>
#include <QTextStream>
#include <QDebug>

namespace git
{

QString getLastCommit()
{
    QString revision = "";
    QProcess process;
    process.start("cmd.exe", QStringList() << "/c"<<"git"<< "rev-parse" << "--verify" << "HEAD");
    if (process.waitForStarted() && process.waitForReadyRead())
        {
            process.waitForFinished();
            revision = QString(process.readAll().constData()).trimmed();
            revision.remove('+');
        }
    return revision;
}

int writeFile(const QString& fileName, const int major, const int minor,
              const int buildNumber, const QString& globalRevision)
{
    // Create a temp file containing the version info and
    // only replace the existing one if they are different
    QTemporaryFile tempFile;
    if (tempFile.open())
        {
            QTextStream out(&tempFile);
            out << "#ifndef VERSION_H\r\n";
            out << "#define VERSION_H\r\n\r\n";
            out << "namespace Version\r\n";
            out << "{\r\n";
            out << "\tstatic const int MAJOR = " << major << ";\r\n";
            out << "\tstatic const int MINOR = " << minor << ";\r\n";
            out << "\tstatic const int BUILD = " << buildNumber << ";\r\n\r\n";
            out << "\tinline const char* versionString()\r\n";
            out << "\t{\r\n";
            out << "\t\treturn \"" << major << '.' << minor << '.' << buildNumber << "\";\r\n";
            out << "\t}\r\n\r\n";
            out << "\tinline const char* globalRevision()\r\n";
            out << "\t{\r\n";
            out << "\t\treturn \"" << globalRevision << "\";\r\n";
            out << "\t}\r\n";
            out << "}\r\n\r\n";
            out << "#endif // VERSION_H\r\n";

            const QString tempFileName = tempFile.fileName();
            tempFile.close();

            if (!QFile::exists(fileName) || utils::readFile(fileName) != utils::readFile(tempFileName))
                {
                    QFile::remove(fileName);
                    QFile::copy(tempFileName, fileName);
                }

            return 0;
        }
    else
        {
            qDebug() << "Error creating temporary file!" ;
            return 1;
        }
}

}
